<template>
  <el-select
    v-model="value"
    v-bind="$attrs"
    collapse-tags
    clearable
    filterable
    @change="change"
  >
    <el-option
      v-for="item in countryCurrencyOptions"
      :key="item.id"
      :label="item.name"
      :value="getValue(item)"
    />
  </el-select>
</template>
<script setup>
import useCommonStore from "@/store/modules/common";
const commonStore = useCommonStore();
const countryCurrencyOptions = computed(() => {
  if (!commonStore.countryCurrencyOptions) {
    commonStore.getCountryCurrencyList();
  }
  return commonStore.countryCurrencyOptions || [];
});

const props = defineProps({
  modelValue: [String, Number, Array],
  valueKey: {
    type: String,
    default: "country",
  },
});

const getValue = (item) => {
  return props.valueKey === "item" ? item : item[props.valueKey];
};

const value = computed({
  get: () => {
    if (JSON.stringify(props.modelValue) == "{}") {
      return [];
    } else {
      return props.modelValue;
    }
  },
  set: (val) => {
    emit("update:modelValue", val);
  },
});

const emit = defineEmits(["update:modelValue", "change"]);
const change = (val) => {
  if (props.valueKey === "item") {
    emit("update:modelValue", val);
  } else {
    const item = countryCurrencyOptions.value.find((i) => i[props.valueKey] == val);
    emit("change", item || "");
    emit("update:modelValue", val);
  }
};

defineExpose({ change });
</script>
